package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR'])
@Transactional(readOnly = true)
class LeadsController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def contactService
    def propertyValuationProviderService

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond Leads.list(params), model: [leadsCount: Leads.count()]
    }

    def show(Leads leads)
    {
        respond leads
    }

    def create()
    {
        respond new Leads(params)
    }

    @Transactional
    def save(Leads leads)
    {
        if (leads == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (leads.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond leads.errors, view: 'create'
            return
        }

        leads.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'leads.label', default: 'Leads'), leads.id])
                redirect leads
            }
            '*' { respond leads, [status: CREATED] }
        }
    }

    def edit(Leads leads)
    {
        respond leads
    }

    @Transactional
    def update(Leads leads)
    {
        if (leads == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (leads.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond leads.errors, view: 'edit'
            return
        }

        leads.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'leads.label', default: 'Leads'), leads.id])
                redirect leads
            }
            '*' { respond leads, [status: OK] }
        }
    }

    @Transactional
    def delete(Leads leads)
    {

        if (leads == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        leads.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'leads.label', default: 'Leads'), leads.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'leads.label',
                                                                                          default: 'Leads'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def searchLeads()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0

        def city = params["city"]
        def district = params["district"]
        def houseType = params["houseType"]
        def specialFactors = params["specialFactors"]

        String sql = "from Leads as u where 1=1"
        if (city)
        {
            sql += " and u.city.name = '${city}'"
        }
        if (district)
        {
            sql += " and u.district like '%${district}%'"
        }
        if (houseType)
        {
            sql += " and u.houseType.name = '${houseType}'"
        }
        if (specialFactors)
        {
            sql += " and u.specialFactors.name = '${specialFactors}'"
        }

        sql += ' order by createdDate desc'

        println "sql:" + sql

        def max = params.max
        def offset = params.offset

        def list = Leads.findAll(sql, [max: max, offset: offset])
        def list1 = Leads.findAll(sql)
        def count = list1.size()

        def leads = new Leads(params)
        respond list, model: [leadsCount: count, leads: leads, params: params], view: 'index'
    }

    // *********************************************************************************************************

    @Secured(['permitAll'])
    @Transactional
    def wxCreate2Step1(String code, String state)
    {
        //comment
        //         def openId = 11
        def openId = session.openId
        if (!openId)
        {
            openId = contactService.setRequest(code, state)
            session.openId = openId
        }

        def leads = new Leads(params)
        leads.openId = openId

        def cityList = []
        def accountCityList = AccountCity.findAll("from AccountCity as a where a.account.name = 'Default'")
        if (accountCityList && accountCityList.size() == 0)
        {
            flash.message = message(code: "暂无开放城市")
        }
        else
        {
            accountCityList.each {
                cityList.add(it.city)
            }
        }

        // respond leads, model: [cityList: cityList]
        respond leads, model: [cityList: cityList], view: 'wxCreate2Step3'
    }

    // @Secured(['permitAll'])
    // @Transactional
    // def wxCreate2Step1()
    // {
    //     def leads = new Leads(params)
    //     leads.openId = "123456"

    //     def cityList = []
    //     def accountCityList = AccountCity.findAll("from AccountCity as a where a.account.id = 1")
    //     if (accountCityList && accountCityList.size() == 0)
    //     {
    //         flash.message = message(code: "暂无开放城市")
    //     }
    //     else
    //     {
    //         accountCityList.each {
    //             cityList.add(it.city)
    //         }
    //     }

    //     respond leads, model: [cityList: cityList]
    // }
    //
    @Secured(['permitAll'])
    @Transactional
    def wxCreate2Step2Pre(Leads leads)
    {
        respond leads, view: "wxCreate2Step2"

    }

    @Secured(['permitAll'])
    @Transactional
    def wxCreate2Step2(Leads leads)
    {
        def projectNameList = []

        // def result = propertyValuationProviderService.searchProjectName(house?.city?.name, house?.projectName)
        def city = leads?.city?.code
        def district = District.findByName(leads?.district)?.code
        def result = propertyValuationProviderService.searchProjectName(city, district, leads?.projectName)
        if (result != 0)
        {
            if (result['code'] in ['-1', '1', '2', '3'])
            {
                flash.message = result['message']
            }
            else
            {
                projectNameList = result['data']
            }
        }

        respond leads, model: [projectNameList: projectNameList], view: "wxCreate2Step2"

    }

    @Secured(['permitAll'])
    @Transactional
    def wxCreate2Step3(Leads leads)
    {
        println params
        def cityList = []
        def accountCityList = AccountCity.findAll("from AccountCity as a where a.account.name = 'Default'")
        if (accountCityList && accountCityList.size() == 0)
        {
            flash.message = message(code: "暂无开放城市")
        }
        else
        {
            accountCityList.each {
                cityList.add(it.city)
            }
        }
        respond leads, model: [cityList: cityList, params: params]
    }

    @Secured(['permitAll'])
    @Transactional
    def wxCreate2Step4Save(Leads leads)
    {
        if (leads == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (leads.hasErrors())
        {
            println leads.errors
            transactionStatus.setRollbackOnly()
            respond leads.errors, view: 'wxCreate2Step3'
            return
        }

        leads.unitPrice = Math.floor(Double.parseDouble(params["unitPrice"]))
        leads.loanAmount = Math.floor(Double.parseDouble(params["unitPrice"]) * leads.area)

        if (leads.validate())
        {
            leads.save flush: true
        }
        else
        {
            println leads.errors
        }

        redirect(action: "wxCreate2Step4", id: leads.id, params: [status: params["status"]])
    }

    @Secured(['permitAll'])
    @Transactional
    def wxCreate2Step4(Leads leads)
    {
        respond leads
    }

    @Secured(['permitAll'])
    @Transactional
    def wxQueryPrice()
    {
        println "==================leads 询值==========================="
        def house = new House()
        house.city = City.findById(params['city'])
        house.district = params['district']
        house.projectName = params['projectName']
        house.building = params['building']
        house.unit = params['unit']
        house.floor = params['floor']
        house.roomNumber = params['roomNumber']
        house.totalFloor = params['totalFloor']
        house.area = Double.parseDouble(params['area'])

        def price = propertyValuationProviderService.appQueryPrice(house)
        if (price != 0)
        {
            println "询值结果："
            println price
            if (price['code'] in ['-1', '1', '2', '3'])
            {
                render([status: "error", errorMsg: price['message'], collateralStatus: "Failed"] as JSON)
            }
            def status = "Completed"
            def unitprice = price['unitprice']
            def saleprice = price['saleprice']
            render([status: "success", price: price, collateralStatus: status] as JSON)
        }
        else
        {
            render([status: "error", errorMsg: "询价失败，请稍后重试", collateralStatus: "Failed"] as JSON)
        }
    }

    @Secured(['permitAll'])
    @Transactional
    def wxCreate3Step1(Leads leads)
    {
        def contact = new Contact()
        respond leads, model: [params: params, contact: contact]
    }

    @Secured(['permitAll'])
    @Transactional
    def wxCreate3Step(String code, String state)
    {
        def openId
        if (session.openId)
        {
            openId = session.openId
        }
        else
        {
            openId = contactService.setRequest(code, state)
            session.openId = openId
        }
        def leads = Leads.findByOpenId(openId)
        def contact = new Contact()
        respond leads, model: [params: params, contact: contact]
    }

    @Secured(['permitAll'])
    @Transactional
    def wxCreate3Step3()
    {
        // 通过手机号码获取用户信息
        Contact contact = Contact.findByCellphoneAndType(params["cellphone"], 'Agent')
        if (contact)
        {
            contact.fullName = params["fullName"]
            contact.cellphone = params["cellphone"]
            contact.openId = params["openId"]
            contact.type = "Agent"
            contact.user = User.findByUsername('liuming')

            contact.save flush: true

            ContactLoginCertificate contactLoginCertificate = new ContactLoginCertificate()
            contactLoginCertificate.contact = contact
            contactLoginCertificate.type = "wechat"
            contactLoginCertificate.externalId = params["openId"]
            if (contactLoginCertificate.validate())
            {
                contactLoginCertificate.save flush: true
            }
            else
            {
                println contactLoginCertificate.errors
            }

            session.openId = params["openId"]

            println "wechat register success"

            def leadsId = params['leadsId']
            def leads = Leads.findById(leadsId)

            def opportunity = new Opportunity()
            opportunity.contact = contact
            opportunity.user = contact?.user
            if (params.accountName)
            {
                opportunity.account = Account.findByName(params.accountName)
            }
            else
            {
                opportunity.account = contact?.user?.account
            }
            opportunity.loanAmount = leads?.loanAmount
            opportunity.unitPrice = leads?.unitPrice
            opportunity.requestedAmount = Double.parseDouble(params['requestedAmount']) * 10000

            opportunity.save flush: true

            def house = new House()
            house.opportunity = opportunity
            house.projectName = leads?.projectName
            house.city = leads?.city
            house.district = leads?.district
            house.building = leads?.building
            house.unit = leads?.unit
            house.roomNumber = leads?.roomNumber
            house.area = leads?.area
            house?.floor = leads?.floor
            house.totalFloor = leads?.totalFloor
            house.unitPrice = leads?.unitPrice
            house.totalPrice = leads?.loanAmount
            house.externalId = leads?.externalId
            house.status = leads?.status
            if (house.validate())
            {
                house.save flush: true
            }
            else
            {
                println house.errors
            }
            println "leads transfer to house"
            println house?.id
            // 验证码验证成功
            respond opportunity, view: 'wxCreate3Step3'

        }
        else
        {
            // 注册失败，请先获取验证码
            flash.message = message(code: 'contact.verifiedCode.getFailed.message')
            respond new Contact(params), model: [params: params], view: 'wxCreate3Step2'
        }
    }

    @Secured(['permitAll'])
    @Transactional
    def wxIndex()
    {
        respond new Leads(), view: 'wxIndex'
    }

    @Secured(['permitAll'])
    @Transactional
    def wxIndex2()
    {
        respond new Leads(), view: 'wxIndex2'
    }
}
